package com.sicpa.web.controller.system;

import com.sicpa.common.constant.Constants;
import com.sicpa.common.core.domain.AjaxResult;
import com.sicpa.common.core.domain.entity.AntiCounterfeitingCaBlacklist;
import com.sicpa.common.core.domain.entity.AntiCounterfeitingRegisteredOffice;
import com.sicpa.common.core.domain.entity.SysMenu;
import com.sicpa.common.core.domain.entity.SysUser;
import com.sicpa.common.core.domain.model.LoginBody;
import com.sicpa.common.core.domain.model.LoginUser;
import com.sicpa.common.core.redis.RedisCache;
import com.sicpa.common.utils.ServletUtils;
import com.sicpa.framework.web.service.SysLoginService;
import com.sicpa.framework.web.service.SysPermissionService;
import com.sicpa.framework.web.service.TokenService;
import com.sicpa.system.service.IAntiCounterfeitingRegisteredOfficeService;
import com.sicpa.system.service.ICaAuthServcie;
import com.sicpa.system.service.ISysMenuService;
import com.sicpa.system.service.ISysUserService;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * 登录验证
 *
 * @author ruoyi
 */
@RestController
public class SysLoginController {

    private SysLoginService loginService;

    private ISysMenuService menuService;

    private SysPermissionService permissionService;

    private TokenService tokenService;

    private RedisCache redisCache;

    private ICaAuthServcie iCaAuthServcie;
    private ISysUserService userService;
    private IAntiCounterfeitingRegisteredOfficeService iAntiCounterfeitingRegisteredOfficeService;

    @Autowired
    public SysLoginController(SysLoginService loginService, ISysMenuService menuService, SysPermissionService permissionService, TokenService tokenService, ICaAuthServcie iCaAuthServcie, RedisCache redisCache, ISysUserService userService, IAntiCounterfeitingRegisteredOfficeService iAntiCounterfeitingRegisteredOfficeService) {
        this.loginService = loginService;
        this.menuService = menuService;
        this.permissionService = permissionService;
        this.tokenService = tokenService;
        this.iCaAuthServcie = iCaAuthServcie;
        this.redisCache = redisCache;
        this.userService = userService;
        this.iAntiCounterfeitingRegisteredOfficeService = iAntiCounterfeitingRegisteredOfficeService;
    }

    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginBody loginBody) {
        AjaxResult ajax = AjaxResult.success();
        String username = loginBody.getUsername();
        //注释掉这些代码可以免ca
        String caSign = loginBody.getCaSign();
        if (StringUtils.isEmpty(caSign)) {
            return AjaxResult.error("CA签名认证失败!");
        }
        if (!iCaAuthServcie.caVerifySignature(caSign)) {
            return AjaxResult.error("CA签名认证失败,ca密码错误!");
        }
        String onlyDistinguish = loginBody.getOnlyDistinguish();
        SysUser sysuser = userService.selectUserByUserName(username);
        if(sysuser == null){
            return AjaxResult.error("用户不存在/密码错误!");
        }
        if (sysuser.getIsOfficeAccount() == 1) {
            //事务所
            Long officeId = sysuser.getOfficeId();
            AntiCounterfeitingRegisteredOffice office = iAntiCounterfeitingRegisteredOfficeService.getDetailById(officeId);
            if (sysuser.getUserName() == null || onlyDistinguish == null || office == null ) {
                return AjaxResult.error("用户账号异常!");
            }
            if (!onlyDistinguish.equals(office.getUnifiedSocialCreditCode())) {
                return AjaxResult.error("该账号用户与usbkey不匹配!");
            }
        } else {
            if (sysuser.getIdCard() == null || onlyDistinguish == null) {
                return AjaxResult.error("用户账号异常!");
            }
            if (!onlyDistinguish.equals(sysuser.getIdCard())) {
                return AjaxResult.error("该账号用户与usbkey不匹配!");
            }
        }
        AntiCounterfeitingCaBlacklist antiCounterfeitingCaBlacklist = new AntiCounterfeitingCaBlacklist();
        antiCounterfeitingCaBlacklist.setOnlyDistinguish(onlyDistinguish);
       // antiCounterfeitingCaBlacklist.setStatus(1);
        //检测是否已经存在序列号，存在不新增，查询，不存在新增
        antiCounterfeitingCaBlacklist.setSerialNumber(loginBody.getSerialNumber());
        List<AntiCounterfeitingCaBlacklist> calist = userService.selectCountUsbkey(antiCounterfeitingCaBlacklist);
        if (calist.size() > 0) {
            //存在
            Integer status = calist.get(0).getStatus();
            if (status == 1) {
                return AjaxResult.error("该账号usbkey已禁用!");
            }
        } else {
            //不存在新增
            antiCounterfeitingCaBlacklist.setStatus(0);
            userService.insertAntiCounterfeitingCaBlacklist(antiCounterfeitingCaBlacklist);
        }
        //注释掉这些代码可以免ca end
        if (Optional.ofNullable(username).isPresent()) {
            Long expire = redisCache.getExpire(Constants.LOGIN_LOCK + username);
            if (expire != null && expire > 0) {
                return AjaxResult.error("该账号已被锁定,锁定时间还剩余" + expire + "分钟!");
            }
            Object loginErrors = redisCache.getCacheObject(Constants.LOGIN_PWD_ERROR_COUNT + username);
            if (loginErrors != null && NumberUtils.toInt(loginErrors.toString()) >= 5) {
                redisCache.setCacheObject(Constants.LOGIN_LOCK + username, 1, 5, TimeUnit.MINUTES);
                redisCache.deleteObject(Constants.LOGIN_PWD_ERROR_COUNT + username);
                return AjaxResult.error("该账号密码输入错误超过5次,已被锁定5分钟!");
            }
        }
        boolean slideStatus = loginBody.getSlideStatus();
        if (!slideStatus) {
            return AjaxResult.error("滑块验证码错误!");
        }
        // 生成令牌
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                loginBody.getUuid());
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public AjaxResult getInfo() {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        SysUser user = loginUser.getUser();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        return ajax;
    }

    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @GetMapping("getRouters")
    public AjaxResult getRouters() {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        // 用户信息
        SysUser user = loginUser.getUser();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(user.getUserId(), user.getIsOfficeAccount());
        return AjaxResult.success(menuService.buildMenus(menus));
    }

}
